package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.ExamSubmission;
import com.lance.answer.gui.answer.gk.answer.lms.util.ImageUtil;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.time.Duration;
import java.util.*;

/**
 * <p>到处某门课程的所有题目<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class ExportLmsQuestionByJSON {


    public static void main(String[] args) throws Exception {
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


        String userName = "1915001252355";
       // String pwd = "Ouchn@19931121";
        String pwd = "Ouchn@2021";
        String subjectName =
                "健康教育与健康促进";
        long courseId = 20000000886L;

        List<Long> submissionIds = Lists.newArrayList();

        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码
        Thread.sleep(10000);

        //webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginId"))).sendKeys(username);

        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();

        Thread.sleep(10000);


        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains(subjectName)) {
                we.findElement(By.tagName("a")).click();
                break;
            }
        }
        Util.switchToLast(driver);


        boolean exportAnswer = true;


        List<Question> questions = Lists.newLinkedList();

        List<String> urlTasks = Lists.newArrayList();
        urlTasks.add("https://lms.ouchn.cn/exam/105938/subjects#/submission/12074051");


        List<ExamSubmission> examSubmissionList = Lists.newArrayList();
        for (String urlTask : urlTasks) {
            driver.get(urlTask);
            Thread.sleep(5000);
            // ng-scope activity-content-bd

            try {

                driver.findElement(By.cssSelector("a[class='view-submission ng-scope']")).click();
            }catch (Exception e){

            }

            Thread.sleep(5000);
            String currentUrl = driver.getCurrentUrl();


            long examId = Long.parseLong(currentUrl.substring(currentUrl.indexOf("/exam/") + 6, currentUrl.indexOf("/subjects")));
            long submissionId = Long.parseLong(currentUrl.substring(currentUrl.indexOf("/submission/") + 12));
            String getUrl = "https://lms.ouchn.cn/api/exams/" + examId + "/submissions/" + submissionId;

            String cookie = Util.getCookie(driver.manage().getCookies());


            Map<String, String> heads = Maps.newHashMap();
            heads.put("referer", "https://lms.ouchn.cn/exam/" + examId + "/subjects");
            heads.put(":method", "GET");
            heads.put(":authority", "lms.ouchn.cn");
            heads.put("cookie", cookie);
            heads.put(":path", "/api/exams/" + examId + "/submissions/" + submissionId);
            heads.put("accept", "application/json, text/plain, */*");

            String result = HttpUtil.get(getUrl, cookie, heads);
            ExamSubmission examSubmission = JSONObject.parseObject(result, ExamSubmission.class);
            examSubmissionList.add(examSubmission);
            System.err.println("Result:::" + result);

            // 每个选项都有自己的一个 optionId, 这里就是获取这个 optionId
            Map<Long, String> optionIdContentMap = Maps.newHashMap();
            for (ExamSubmission.SubjectsDataDTO.SubjectsDTO subjectsDTO : examSubmission.getSubjectsData().getSubjects()) {

                for (ExamSubmission.SubjectsDataDTO.SubjectsDTO.Option option : subjectsDTO.getOptions()) {
                    optionIdContentMap.put(option.getId(), option.getContent());
                }
            }

            // 根据每个题目的ID  subjectId来获取答案
            Map<Long, List<String>> subjectAnswerMap = Maps.newHashMap();
            for (ExamSubmission.SubmissionDataDTO.SubjectsDTO submissionSubjectDTO : examSubmission.getSubmissionData().getSubjects()) {
                if (submissionSubjectDTO == null) {
                    continue;
                }
                List<String> answerLists = Lists.newArrayList();
                // 获取填空题的答案
                if (submissionSubjectDTO.getAnswers() != null) {
                    for (ExamSubmission.SubmissionDataDTO.SubjectsDTO.AnswersDTO answersDTO : submissionSubjectDTO.getAnswers()) {
                        answerLists.add(answersDTO.getContent());
                    }
                }
                // 获取简单题的答案  --不对 这个是选中的选项，不是正确的答案！！！！！！！
                if (submissionSubjectDTO.getAnswerOptionIds() != null) {
                    for (Long optionId : submissionSubjectDTO.getAnswerOptionIds()) {
                        answerLists.add(optionIdContentMap.get(optionId));
                    }
                }
                subjectAnswerMap.put(submissionSubjectDTO.getSubjectId(), answerLists);
            }


            // 找到题目的ID，并根据subjectAnswerMap获取答案
            for (ExamSubmission.SubjectsDataDTO.SubjectsDTO subjectsDTO : examSubmission.getSubjectsData().getSubjects()) {


                Question question = new Question();
                questions.add(question);
                // 题目类型
                String questionType = subjectsDTO.getType();
                System.err.println("questionType:" + questionType);
                try {
                    if (questionType.equals("subject ng-scope text")) {
                        continue;
                    }
                    setQuestionType(question, questionType);
                } catch (Exception exception) {
                    exception.printStackTrace();
                    continue;
                }

                String title = subjectsDTO.getDescription();
                //  title = Util.dealContent(title);
                question.setTitle(title);

                try {
                    String[] correctArray = new String[]{};

                    correctArray = subjectAnswerMap.get(subjectsDTO.getId()).toArray(correctArray);
                    question.setCorrectArray(correctArray);
                } catch (Exception e111) {

                }

            }


        }

        // 输出JSON文件；  {id}-题型.json
        Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", DealJsonString.delHTMLTag(question.getTitle()));
            answerMap.put("originTitle", question.getTitle());
            answerMap.put("questionCode", MD5Utils.encode(subjectName + question.getTitle()));
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());
            if (question.getCorrectArray() != null && question.getCorrectArray().length > 0) {
                answerMap.put("answers", question.getCorrectArray());
            } else {
                answerMap.put("answers", question.getCorrectArray());
            }
            // 如果这里是完形填空  就默认为sendKeys
            if (question.getQuestionType() == 6) {
                answerMap.put("answerType", "send");
            } else {
                answerMap.put("answerType", "click");
            }

            answers.add(answerMap);
        }
        String rootPath = "d://lmsTmp//";
        FileUtils.write(new File(rootPath + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");
        FileUtils.write(new File(rootPath + "//origin//" + subjectName + ".json"), JSONObject.toJSONString(examSubmissionList, SerializerFeature.PrettyFormat), "utf-8");

        Thread.sleep(5000);

        Thread.sleep(500000000);

//
    }

    public static void setQuestionType(Question question, String type) throws Exception {
        switch (type) {
         //   case "subject ng-scope fill_in_blank":
            case "fill_in_blank":
                question.setQuestionType(4);
                question.setQuestionTypeDesc("填空题");
                break;
           // case "subject ng-scope single_selection":
            case "single_selection":
                question.setQuestionType(1);
                question.setQuestionTypeDesc("单选题");
                break;
            case "multiple_selection":
                question.setQuestionType(2);
                question.setQuestionTypeDesc("多选题");
                break;
            case "true_or_false":
                question.setQuestionType(3);
                question.setQuestionTypeDesc("判断题");
                break;
            case "short_answer":
                question.setQuestionType(5);
                question.setQuestionTypeDesc("简答题");
                break;
            //subject ng-scope cloze
            case "subject ng-scope cloze":
                question.setQuestionType(6);
                question.setQuestionTypeDesc("完形填空");
                break;
            default:
               // throw new Exception("当前题型不支持自动答题！");
                question.setQuestionType(0);
                question.setQuestionTypeDesc(type);
        }
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
